package com.itljm.cxrMarket.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itljm.cxrMarket.entity.Products;
import com.itljm.cxrMarket.entity.ShoppingCart;
import com.itljm.cxrMarket.entity.dto.ShoppingCartDTO;
import com.itljm.cxrMarket.mapper.ProductsMapper;
import com.itljm.cxrMarket.service.ProductsService;
import com.itljm.cxrMarket.service.ShoppingCartService;
import com.itljm.cxrMarket.mapper.ShoppingCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService{

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ProductsService productsService;
    @Autowired
    private ProductsMapper productsMapper;

    @Override
    public boolean addProductToCart(Long userId, Integer productId) {
        // 先查询商品库存是否足够
        if (productsMapper.getStockQuantity(productId) <= 0) {
            return false;
        }
        // 再查询购物车中是否已有该商品，如果有则增加数量
        int i = shoppingCartMapper.increaseProductQuantity(userId, productId);
        if (i>0) return true;
        // 若没有，则新增记录
        return shoppingCartMapper.addProductToCart(userId, productId)>0;
    }

    @Override
    public boolean increaseProductQuantity(Long userId, Integer productId, Integer quantity) {
        // 查询商品库存是否足够
        Products product = productsService.selectProductById(productId);
        if (product == null || product.getStockQuantity() <= quantity) {
            return false;
        }
        return shoppingCartMapper.increaseProductQuantity(userId, productId)>0;
    }

    @Override
    public boolean decreaseProductQuantity(Long userId, Integer productId) {
        // 先尝试减少商品数量
        int i = shoppingCartMapper.decreaseProductQuantity(userId, productId);
//        // 如果商品数量为1，则移除记录
//        int j = shoppingCartMapper.removeProductFromCart(userId, productId);

        return i>0;
    }

    @Override
    public boolean removeProductFromCart(Long userId, Integer productId) {
        return shoppingCartMapper.removeProductFromCartById(userId, productId)>0;
    }

    @Override
    public List<ShoppingCartDTO> getShoppingCartItems(Long userId) {
        return shoppingCartMapper.getShoppingCartItems(userId);
    }

    @Override
    public boolean updateCheckedStatus(Long userId, Integer productId, Integer checked) {
        return shoppingCartMapper.updateCheckedStatus(userId, productId, checked)>0;
    }

}




